/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.siseventos.dao.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Buscando o Session Factory a partir do Spring
            ApplicationContext contexto = new ClassPathXmlApplicationContext("applicationContext.xml");
            sessionFactory = (SessionFactory) contexto.getBean("sessionFactory");

            // Criando o SessionFactory
            /*
             * Configuration cfg = new Configuration().configure();
             * ServiceRegistry sr = new
             * ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
             * sessionFactory = cfg.buildSessionFactory(sr);
             */


        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getSession()throws HibernateException {
        Session sess = null;
        try {
            sess = sessionFactory.getCurrentSession();
        } catch (org.hibernate.HibernateException he) {
            sess = sessionFactory.openSession();
        }
        return sess;
    }
}
